<template>
  <Dialog v-model="dialogVisible" title="迁移">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="迁移目标" prop="targetSysId">
        <el-tree-select
          v-model="formData.targetSysId"
          :data="deptTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请选择迁移目标"
          value-key="deptId"
          @change="getLabel"
        />
      </el-form-item>
      <el-form-item label="迁移内容" prop="transferType">
        <el-select v-model="formData.transferType" placeholder="请选择迁移内容">
          <el-option label="全部" value="0" />
          <el-option label="资产迁移" value="1" />
          <el-option label="用户迁移" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-bottom: 10px">
        <div style="color: #cccccc">
          <Icon icon="svg-icon:tips" style="vertical-align: middle" />
          迁移后当前应用系统涉及的人员、资产归属将变更为迁移目标，请谨慎操作！
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { defaultProps, handleTree } from '@/utils/tree'
import * as SystemApi from '@/api/system/infoSystem'
import { assetMessageTransferSys } from '@/api/assetList'

defineOptions({ name: 'SystemDeptForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  targetSysId: undefined,
  transferType: ''
})
const formRules = reactive({
  targetSysId: [{ required: true, message: '迁移目标不能为空', trigger: 'blur' }],
  transferType: [{ required: true, message: '迁移内容不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const deptTree = ref() // 树形结构
const targetSysName = ref()
const sourceSysName = ref()
const sourceSysId = ref()
/** 打开弹窗 */
const open = async (id: number, name: String) => {
  dialogVisible.value = true
  sourceSysId.value = id
  sourceSysName.value = name

  resetForm()
  // 获得机构树
  await getTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    // const data = formData.value as unknown as DeptApi.DeptVO
    // data.sourceSysId = sourceSysId.value
    const data = {
      ...formData.value,
      sourceSysId: sourceSysId.value,
      targetSysName: targetSysName.value,
      sourceSysName: sourceSysName.value
    }
    await assetMessageTransferSys(data)
    message.success('操作成功')

    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

function findLabelByValue(data, value) {
  // 当前层级查找对应id的label
  for (let i = 0; i < data.length; i++) {
    if (data[i].id == value) {
      return data[i].name
    }
    //如果找不到则递归查找children
    if (data[i].children?.length > 0) {
      const result = findLabelByValue(data[i].children, value)
      if (result) return result
    }
  }
  return null
}

const getLabel = (v) => {
  targetSysName.value = findLabelByValue(deptTree.value, v)
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    targetSysId: undefined
  }
  formRef.value?.resetFields()
}

/** 获得机构树 */
const getTree = async () => {
  deptTree.value = []
  const data = await SystemApi.getInfoSystemPage({ pageSize: -1 })
  const deptData = data.map((item) => {
    if (item.id === sourceSysId.value) {
      item.disabled = true
    }
    return item
  })
  let dept: Tree = { id: 0, name: '顶级机构', children: [] }
  dept.children = handleTree(deptData)
  deptTree.value.push(dept)
}
</script>
